//
//  AFFRichTextImage.m
//  AnyfishApp
//
//  Created by Bob Lee on 14-4-18.
//  Copyright (c) 2014年 Anyfish. All rights reserved.
//

#import "AFFRichTextImage.h"
#import <CoreText/CoreText.h>

static const float kZoom = 1.2f;

@implementation AFFRichTextImage

- (void)replaceTextWithAttributedString:(NSMutableAttributedString*) attString
{
    //删除替换的占位字符
    [attString deleteCharactersInRange:self.range];
    
    CTRunDelegateCallbacks expCallbacks;
    expCallbacks.version      = kCTRunDelegateVersion1;
    expCallbacks.dealloc      = AFFRichTextExpDelegateDeallocCallback;
    expCallbacks.getAscent    = AFFRichTextExpDelegateGetAscentCallback;
    expCallbacks.getDescent   = AFFRichTextExpDelegateGetDescentCallback;
    expCallbacks.getWidth     = AFFRichTextExpDelegateGetWidthCallback;
    
    NSMutableAttributedString *imageAttributedString = [[NSMutableAttributedString alloc] initWithString:@" "];
    
    //
    CTRunDelegateRef runDelegate = CTRunDelegateCreate(&expCallbacks, (__bridge void*)self);
    [imageAttributedString addAttribute:(NSString *)kCTRunDelegateAttributeName value:(__bridge id)runDelegate range:NSMakeRange(0, 1)];
    CFRelease(runDelegate);
    
    [attString insertAttributedString:imageAttributedString atIndex:self.range.location];
    
    [super replaceTextWithAttributedString:attString];
}

#pragma mark - RunDelegateCallback

void AFFRichTextExpDelegateDeallocCallback(void *refCon)
{
    
}

//--上行高度
CGFloat AFFRichTextExpDelegateGetAscentCallback(void *refCon)
{
    AFFRichTextImage *run =(__bridge AFFRichTextImage *) refCon;
    return run.originalFont.ascender * kZoom;
}

//--下行高度
CGFloat AFFRichTextExpDelegateGetDescentCallback(void *refCon)
{
    AFFRichTextImage *run =(__bridge AFFRichTextImage *) refCon;
    return run.originalFont.descender * kZoom;
}

//-- 宽
CGFloat AFFRichTextExpDelegateGetWidthCallback(void *refCon)
{
    AFFRichTextImage *run =(__bridge AFFRichTextImage *) refCon;
    return (run.originalFont.ascender - run.originalFont.descender) * kZoom;
}

@end